package com.zkingsoft.async;


import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONObject;
import com.matrix.async.core.TaskHandler;
import com.matrix.core.tools.LogUtil;
import com.matrix.core.tools.PropertiesUtil;
import com.matrix.core.tools.StringUtils;
import com.matrix.core.tools.UUIDUtil;
import com.zkingsoft.bean.BizActivities;
import com.zkingsoft.bean.BizCollageDetail;
import com.zkingsoft.bean.BizCollageInfo;
import com.zkingsoft.bean.BizIncomeLog;
import com.zkingsoft.bean.BizMyCoupon;
import com.zkingsoft.bean.BizOrder;
import com.zkingsoft.bean.BizUser;
import com.zkingsoft.common.bean.SysUsers;
import com.zkingsoft.common.constance.AppConstance;
import com.zkingsoft.dao.BizCollageInfoDao;
import com.zkingsoft.dao.BizIncomeLogDao;
import com.zkingsoft.dao.BizMyCouponDao;
import com.zkingsoft.dao.BizUserDao;
import com.zkingsoft.externalInterface.weixinUtil.WeixinServiceUtil;
import com.zkingsoft.redis.RedisUserLoginUtils;
import com.zkingsoft.service.BizActivitiesService;
import com.zkingsoft.service.BizCollageDetailService;
import com.zkingsoft.service.BizCollageInfoService;
import com.zkingsoft.service.BizMyCouponService;
import com.zkingsoft.service.BizOrderService;
import com.zkingsoft.tools.CodeUtil;
import com.zkingsoft.tools.WxUtils;

public class UpdatePayHandler implements TaskHandler {
	private static final long serialVersionUID = -2719945289184242205L;

	@Autowired
	private WeixinServiceUtil weixinServiceUtil;
	@Autowired
	private BizCollageDetailService bizCollageDetailService;
	@Autowired
	RedisUserLoginUtils redisUserLoginUtils;
	@Autowired
	private BizMyCouponService bizMyCouponService;
	@Autowired
	private BizActivitiesService activitiesService;
	@Autowired
	private BizOrderService bizOrderService;
	@Autowired
	private BizCollageInfoService bizCollageInfoService;
	@Autowired
	private BizCollageInfoDao bizCollageInfoDao;
	@Autowired
	private BizUserDao bizUserDao;
	@Autowired
	private BizIncomeLogDao bizIncomeLogDao;
	@Autowired
	private BizMyCouponDao bizMyCouponDao;
	@Override
	public boolean execute(Map<String, String> dataMap) {
		
		String orderId = dataMap.get("orderId");
		String orderNo = dataMap.get("orderNo");
		String payMoney = dataMap.get("payMoney");
		LogUtil.debug("#更新支付信息任务开始执行#订单ID#{}#订单号#{}#支付金额#{}",orderId,orderNo,payMoney);
		BizOrder order=new BizOrder();
        order.setOrderId(orderId);
       /* order.setPayMoney(payMoney);*/
        order.setOrderNo(orderNo);
        order.setPayStatus(AppConstance.PAY_STATUS_SUC);
        LogUtil.debug("#更新支付信息任务结束#订单ID#{}",orderId);
		return addActInfo(order);
	}

	
	 /**
	   * 
	   * @Desoription  支付成功后生成活动信息
	   * @author  何明
	   * @param  order
	   * @return boolean
	   * @date  2018年07月07日
	   */
	  @Transactional
	  private boolean addActInfo( BizOrder order){
		  //查询订单信息
		 BizOrder bizOrder=bizOrderService.findById(order.getOrderId());
		  
		  
		  //核对订单编号,支付金额  !bizOrder.getPayMoney().equals(order.getPayMoney())
		  if(bizOrder==null || !bizOrder.getOrderNo().equals(order.getOrderNo())){
			  LogUtil.debug("订单信息核对失败---提交订单：{}---查询订单：{}", order,bizOrder);
			  return false;
		  }
		  //拼团活动
		  if(AppConstance.ACTIVITIES_COLLAGE==bizOrder.getOrderType()){
			  //获取备注信息
			  BizOrder remark=JSONObject.parseObject(bizOrder.getOrderRemark(), BizOrder.class);
			  LogUtil.debug("获取到的订单备注信息:{}",remark);
			  //查询活动
			  BizActivities act=activitiesService.queryById(remark.getActId());
			  //已参团人数 
			  int hasnum=0;
			  //如果没有团ID，就是团长开团
			  BizCollageInfo collInfo;
			  if(StringUtils.isBlank(remark.getCinfoId())){
				  //新增开团信息
				  collInfo=new BizCollageInfo();
				  collInfo.setCreateBy(bizOrder.getUserId());
				  collInfo.setUpdateBy(bizOrder.getUserId());
				  collInfo.setCinfoId(UUIDUtil.getRandomID());
				  //获取已有的最大团编号
				  int maxNum= bizCollageInfoDao.getMaxCinfoNum(remark.getActId());
				  collInfo.setCinfoNum(String.valueOf((maxNum+1)));
				  collInfo.setCinfoUserId(bizOrder.getUserId());
				  collInfo.setCinfoType(remark.getCinfoType());
				  collInfo.setColId(remark.getColId());
				  collInfo.setCinfoPrice(remark.getCinfoPrice());
				  collInfo.setCinfoStatus(AppConstance.COLLAGE_STATUS_WCT);
				  bizCollageInfoService.add(collInfo);
			  }else{
				  //查询开团信息
				  collInfo=bizCollageInfoDao.selectById(remark.getCinfoId());
				  if(collInfo==null){
					  LogUtil.debug("获取团信息失败#团ID：{}", remark.getCinfoId());
					  return false;
				  }
				//已参团人数 
				 hasnum=collInfo.getHasNum();
			  }
			 //添加参团信息详情
			  BizCollageDetail bizCollageDetail=new BizCollageDetail();
			  bizCollageDetail.setActId(remark.getActId());
			  bizCollageDetail.setCreateBy(bizOrder.getUserId());
			  bizCollageDetail.setUpdateBy(bizOrder.getUserId());
			  bizCollageDetail.setDetId(UUIDUtil.getRandomID());
			  bizCollageDetail.setCinfoId(collInfo.getCinfoId());
			  bizCollageDetail.setUserId(bizOrder.getUserId());
			  bizCollageDetail.setOrderId(bizOrder.getOrderId());
			  bizCollageDetail.setDetStatus(AppConstance.DET_STATUS_WCT);
			  bizCollageDetail.setCouponId(remark.getCouId());
			  bizCollageDetail.setDetUserInfo(remark.getActCustomForm());
			 bizCollageDetailService.add(bizCollageDetail);
			 //更新我的优惠券状态：已使用
			 if(StringUtils.isNotBlank(remark.getCouId())){
				 BizMyCoupon bizMyCoupon=new BizMyCoupon();
				 bizMyCoupon.setMcouId(remark.getCouId());
				 bizMyCoupon.setMcouStatus(AppConstance.MCOU_STATUS_YSY);
				 bizMyCouponDao.updateByModel(bizMyCoupon);
			 }
			 		//如果参团人数达到已成团标准，更新团状态已成团
				  if(hasnum+1>=Integer.parseInt(collInfo.getCinfoType())){
					  LogUtil.debug("人数达到标准，更新团状态为已成团:{}",hasnum+1);
					  collInfo=new BizCollageInfo();
					  collInfo.setCinfoId(bizCollageDetail.getCinfoId());
					  collInfo.setCinfoStatus(AppConstance.COLLAGE_STATUS_YCT);
					 int j= bizCollageInfoService.modifyByModel(collInfo);
					 if(j>0){
						 //更新此团详情信息（生成二维码，验证码，收入记录）
						 updateCollDetail(bizCollageDetail.getCinfoId(),act.getUserId());
						  
					 }
				  }
		  }
		  //更新订单状态为支付成功
		 int i=bizOrderService.modifyByModel(order);
		if(i>0){
			 return true;
		}
		 return false;
	  }
	  
	  /**
	   * 更新已成团详情信息
	   */
	private void updateCollDetail(String cinfoId,String actUserId){
		 //团收入 
		 BigDecimal totalIncome=new BigDecimal("0");
		//查询所有团详情信息，生成二维码
		  LogUtil.debug("==============生成二维码");
		  BizCollageDetail detail=new BizCollageDetail();
		  detail.setCinfoId(cinfoId);
		  List<BizCollageDetail> detailList=
		  bizCollageDetailService.findByModel(detail);
		  for(BizCollageDetail collDet:detailList){
			  totalIncome=totalIncome.add(collDet.getPayMoney());
			  try {
				// 生成二维码
				String saveUrl = PropertiesUtil.getString(AppConstance.NGINX_URL);
				String codeUrl=CodeUtil.encode(saveUrl+"/do/wxCommon/verify/"+collDet.getDetId(), 
						null,  true, "");
				collDet.setDetQrcode(codeUrl);
				//更新状态为待使用
				collDet.setDetStatus(AppConstance.DET_STATUS_DSY);
				//生成验证码
				collDet.setDetNumcode(WxUtils.getNumCode());
				bizCollageDetailService.modifyByModel(collDet);
			  } catch (Exception e) {
				LogUtil.error("生成二维码异常", e, "");
				
			}
			  
		  } 
		  
		  synchronized (this) {
			  //查询用户余额
			  BigDecimal userMoney=bizUserDao.selectUserMoney(actUserId);
			  //生成收入记录
			  BizIncomeLog bizIncomeLog=new BizIncomeLog();
				bizIncomeLog.setIncId(UUIDUtil.getRandomID());
				bizIncomeLog.setCreateBy(actUserId);
				bizIncomeLog.setUpdateBy(actUserId);
				bizIncomeLog.setUserId(actUserId);
				bizIncomeLog.setIncType(AppConstance.INCTYPE_COL);
				bizIncomeLog.setActInfoId(cinfoId);
				bizIncomeLog.setIncMoney(totalIncome);
				bizIncomeLogDao.insert(bizIncomeLog);
				//更新用户余额
				userMoney=userMoney.add(totalIncome);
				LogUtil.debug("totalIncome:{}", totalIncome);
				LogUtil.debug("userMoney:{}", userMoney);
				BizUser bizUser=new BizUser();
				bizUser.setUserId(actUserId);
				bizUser.setUserMoney(userMoney);
				bizUserDao.updateMoney(bizUser);
		}
		 
			
	}
	

	@Override
	public void onError(Map<String, String> dataMap, Exception e) {

	}

}
